package hoodoos.rule.script.jython;

import hoodoos.rule.api.Facts;
import hoodoos.rule.api.GlobalContext;
import hoodoos.rule.api.RequestContext;
import hoodoos.rule.core.BasicRule;
import org.python.core.PyBoolean;
import org.python.core.PyClass;
import org.python.core.PyObject;

public class JythonRule extends BasicRule {

  private PyClass pyClass;

  private PyObject pyObject;

  public JythonRule(String name, PyClass pyClass) {
    super(name);
    this.pyClass = pyClass;
    this.pyObject = pyClass.__call__();
  }

  @Override
  public void init() {
    pyClass.invoke("init", pyObject);
  }

  @Override
  public boolean evaluate(GlobalContext globalContext, RequestContext requestContext) {
    PyObject[] args = new PyObject[]{new PyGlobalContext(globalContext), new PyRequestContext(requestContext)};
    PyObject evaluate = pyClass.invoke("evaluate", pyObject, args, new String[]{"global_context", "request_context"});
    return ((PyBoolean) evaluate).getBooleanValue();
  }

  @Override
  public void execute(GlobalContext globalContext, RequestContext requestContext, Facts facts) throws Exception {
    PyFacts pyFacts = new PyFacts(facts);
    PyObject[] args = new PyObject[]{new PyGlobalContext(globalContext), new PyRequestContext(requestContext), pyFacts};
    pyClass.invoke("execute", pyObject, args, new String[]{"global_context", "request_context", "facts"});
  }
}
